package com.mxpio.erp.technology.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.googlecode.aviator.AviatorEvaluator;
import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.inventory.entity.VInvStock;
import com.mxpio.erp.common.inventory.service.VInvStockService;
import com.mxpio.erp.common.inventory.vo.InvLotStockVO;
import com.mxpio.erp.common.technology.entity.*;
import com.mxpio.erp.common.technology.service.BomInfoService;
import com.mxpio.erp.common.technology.vo.*;
import com.mxpioframework.common.exception.MBootException;
import com.mxpioframework.common.util.BeanReflectionUtils;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.lin.Linq;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BomInfoServiceImpl extends BaseServiceImpl<BomInfo> implements BomInfoService {

    @Autowired
    private VInvStockService invStockService;
    private static final Logger logger = LoggerFactory.getLogger(BomInfoServiceImpl.class);

    @Transactional(
            readOnly = false
    )
    @Override
    public List<BomInfo> listByDate(String dateStr) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = null;
        try {
            date = dateFormat.parse(dateStr);
        } catch (Exception e) {
            throw new MBootException("日期" + dateStr + "不合法");
        }
        List<BomInfo> bomInfoList = JpaUtil.linq(BomInfo.class).lessThanOrEqualTo("beginTime", date).greaterThan("endTime", date).list();
        if (CollectionUtils.isEmpty(bomInfoList)) {
            return bomInfoList;
        }

        for (BomInfo bomInfo : bomInfoList) {
            List<BomInfoLine> bomInfoLineList = JpaUtil.linq(BomInfoLine.class).equal("bomId", bomInfo.getParentCode()).list();
            if (CollectionUtils.isEmpty(bomInfoLineList)) {
                continue;
            }
            Date bomBeginTime = bomInfo.getBeginTime();
            if (bomInfo.getBomInfoLineList() == null) {
                bomInfo.setBomInfoLineList(new ArrayList<>());
            }
            for (BomInfoLine line : bomInfoLineList) {
                if (line.getBeginTime().compareTo(bomBeginTime) <= 0 && line.getEndTime().compareTo(bomBeginTime) >= 0) {
                    bomInfo.getBomInfoLineList().add(line);
                }
            }
        }
        return bomInfoList;
    }

    @Transactional(
            readOnly = false
    )
    @Override
    public Result<BomInfo> updateBomStatus(BomInfo bomInfo, OrderStatusEnums.BomStatus bomStatus) {
        bomInfo.setUseType(bomStatus.getStatusCode());
        this.update(bomInfo);
        return Result.OK();
    }


    @Transactional
    @Override
    public BomInfo listBom(String itemCode, VersionVO vo,boolean handleVirtualPartFlag) {//handleVirtualPartFlag 是否处理转化虚拟机
        List<Item> itemList = JpaUtil.linq(Item.class).equal("itemCode", itemCode).equal("itemSource", "1").list();
        if (CollectionUtils.isEmpty(itemList)) {
            return new BomInfo();
        }
        Item item = itemList.get(0);
        List<BomInfo> bomInfoList;
        if (vo.getDate() != null) {
            bomInfoList = JpaUtil.linq(BomInfo.class).equal("parentCode", itemCode).lessThanOrEqualTo("beginTime", vo.getDate()).greaterThan("endTime", vo.getDate()).list();
        } else if (StringUtils.isNotBlank(vo.getVersion())) {
            bomInfoList = JpaUtil.linq(BomInfo.class).equal("parentCode", itemCode).equal("version", vo.getVersion()).list();
        } else {
            bomInfoList = JpaUtil.linq(BomInfo.class).equal("parentCode", itemCode).equal("primaryBom", "1").list();
        }

        BomInfo bomInfo;
        if (CollectionUtils.isEmpty(bomInfoList)) {
            bomInfo = new BomInfo();
            bomInfo.setParentCode(item.getItemCode());
            bomInfo.setParentName(item.getItemName());
            bomInfo.setParentGroup(item.getItemGroupCode());
            bomInfo.setParentSpec(item.getItemSpec());
            bomInfo.setParentUnit(item.getUnitCode());
            bomInfo.setParentDrawingNo(item.getDrawingNo());
        } else {
            bomInfo = bomInfoList.get(0);
            List<BomInfoLine> lineList = JpaUtil.linq(BomInfoLine.class).equal("bomId", bomInfo.getParentCode()).lessThanOrEqualTo("beginTime", bomInfo.getBeginTime()).greaterThan("endTime", bomInfo.getBeginTime()).list();
            if (handleVirtualPartFlag){
                List<BomInfoLine> allInfoLines = new ArrayList<>();
                getAllBomInfoLine(allInfoLines,lineList,vo);//查询所有的bominfoline，其中虚拟件需要转换为对应的bom
                bomInfo.setBomInfoLineList(allInfoLines);
            }else{
                bomInfo.setBomInfoLineList(lineList);
            }

        }
        return bomInfo;
    }

    private void getAllBomInfoLine(List<BomInfoLine> returnLines,List<BomInfoLine> sourceLines,VersionVO vo){//处理bomline物料有虚拟件类型物料时
        if (sourceLines == null||sourceLines.size()==0){
            return;
        }
        for (BomInfoLine line:sourceLines){
            String itemCode = line.getItemCode();
            Item item = JpaUtil.linq(Item.class).idEqual(itemCode).findOne();
            if(item==null){
                throw new MBootException("物料编码："+itemCode+"对应的物料不存在，请检查数据！");
            }
            if ("1".equals(item.getVirtualPart())){//虚拟件
                List<BomInfo> bomInfoList;
                if (vo.getDate() != null) {
                    bomInfoList = JpaUtil.linq(BomInfo.class).equal("parentCode", itemCode).lessThanOrEqualTo("beginTime", vo.getDate()).greaterThan("endTime", vo.getDate()).list();
                } else if (StringUtils.isNotBlank(vo.getVersion())) {
                    bomInfoList = JpaUtil.linq(BomInfo.class).equal("parentCode", itemCode).equal("version", vo.getVersion()).list();
                } else {
                    bomInfoList = JpaUtil.linq(BomInfo.class).equal("parentCode", itemCode).equal("primaryBom", "1").list();
                }
                BomInfo bomInfo;
                if (!CollectionUtils.isEmpty(bomInfoList)) {
                    bomInfo = bomInfoList.get(0);
                    List<BomInfoLine> lineList = JpaUtil.linq(BomInfoLine.class).equal("bomId", bomInfo.getParentCode()).lessThanOrEqualTo("beginTime", bomInfo.getBeginTime()).greaterThan("endTime", bomInfo.getBeginTime()).list();
                    getAllBomInfoLine(returnLines,lineList,vo);//递归
                }
            }else{
                returnLines.add(line);
            }
        }
    }

    @Override
    @Transactional(readOnly = false)
    public List<BomInfo> listHistory(String itemCode) {
        List<BomInfo> bomInfoList = JpaUtil.linq(BomInfo.class).equal("parentCode", itemCode).asc("beginTime").list();
        if (CollectionUtils.isEmpty(bomInfoList)) {
            return bomInfoList;
        }
        List<BomInfoLine> bomInfoLineList = JpaUtil.linq(BomInfoLine.class).equal("bomId", itemCode).list();
        if (CollectionUtils.isEmpty(bomInfoLineList)) {
            return bomInfoList;
        }

        for (BomInfo bomInfo : bomInfoList) {
            Date bomBeginTime = bomInfo.getBeginTime();
            if (bomInfo.getBomInfoLineList() == null) {
                bomInfo.setBomInfoLineList(new ArrayList<>());
            }
            for (BomInfoLine line : bomInfoLineList) {
                if (line.getBeginTime().compareTo(bomBeginTime) <= 0 && line.getEndTime().compareTo(bomBeginTime) >= 0) {
                    bomInfo.getBomInfoLineList().add(line);
                }
            }
        }

        /*Map<Date,BomInfo> bomInfoMap = JpaUtil.index(bomInfoList,"beginTime");
        for(BomInfoLine line:bomInfoLineList){
            BomInfo bomInfo = bomInfoMap.get(line.getBeginTime());
            if(bomInfo==null){
                continue;
            }
            if(bomInfo.getBomInfoLineList()==null){
                bomInfo.setBomInfoLineList(new ArrayList<>());
            }
            bomInfo.getBomInfoLineList().add(line);
        }*/
        return bomInfoList;
    }

    @Override
    @Transactional
    public Page<BomInfo> page(Pageable page, Criteria c) {

        Page<Item> itemPage = JpaUtil.linq(Item.class).where(c).equal("itemSource", "1").paging(page);
        Long count = JpaUtil.linq(Item.class).where(c).equal("itemSource", "1").count();
        List<Item> itemList = itemPage.getContent();
        Set<String> itemCodes = JpaUtil.collect(itemList, "itemCode");
        List<BomInfo> bomInfoList = JpaUtil.linq(BomInfo.class).in("parentCode", itemCodes).equal("primaryBom", "1").list();
        Map<String, BomInfo> bomMap = JpaUtil.index(bomInfoList, "parentCode");
        List<BomInfo> returnList = new ArrayList<>();
        for (Item item : itemList) {
            BomInfo bomInfo = bomMap.get(item.getItemCode());
            if (Objects.isNull(bomInfo)) {
                bomInfo = new BomInfo();
            }
            bomInfo.setParentCode(item.getItemCode());
            bomInfo.setParentName(item.getItemName());
            bomInfo.setParentGroup(item.getItemGroupCode());
            bomInfo.setParentSpec(item.getItemSpec());
            bomInfo.setParentUnit(item.getUnitCode());
            bomInfo.setParentDrawingNo(item.getDrawingNo());
            returnList.add(bomInfo);
        }
        return new PageImpl<>(returnList, page, count);
    }

    @Override
    @Transactional
    public ImmutablePair<String, String> consumption(ConsumptionVO vo) {
        List<ItemMaterialProp> props = JpaUtil.linq(ItemMaterialProp.class).equal("code", vo.getItemCode()).equal("propType", "item").list();
        if (CollectionUtils.isEmpty(props)) {
            String msg = "未找到编码为[" + vo.getItemCode() + "]的物料属性";
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>{}", msg);
            return new ImmutablePair<>(null, msg);
        }

        ItemMaterialProp prop = props.get(0);
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>ItemMaterialProp:{}", JSON.toJSONString(prop));
        List<ConsumptionExp> expList = JpaUtil.linq(ConsumptionExp.class).equal("materialType", prop.getMaterialType()).list();
        if (CollectionUtils.isEmpty(expList)) {
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>ConsumptionExp is empty");
            return new ImmutablePair<>("0", null);
        }

        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>ConsumptionExp-MaterialType:{},Expression:{}", expList.get(0).getMaterialType(), expList.get(0).getExpression());

        Map<String, Object> env = new HashMap<>();
        env.put("L", vo.getMakeLength());//BomInfoLine:下料长度
        env.put("q", vo.getMakeNum());//BomInfoLine:可制数量
        env.put("s", vo.getMakeArea());//BomInfoLine:下料面积
        env.put("a", prop.getMaterialDensity());//物料材料属性:密度（g/cm3）
        env.put("R", prop.getMaterialDiameter());//物料材料属性:直径（mm）
        env.put("r", prop.getMaterialThickness());//物料材料属性:壁厚（mm）
        BigDecimal result = new BigDecimal(AviatorEvaluator.execute(expList.get(0).getExpression(), env).toString()).setScale(2, RoundingMode.CEILING);
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>result:{}", result.toPlainString());
        return new ImmutablePair<>(result.toPlainString(), null);
    }

    @Transactional
    @Override
    public void clacAll() {
        List<BomInfoLine> bomInfoLines = JpaUtil.linq(BomInfoLine.class).le("itemConsumption", BigDecimal.ZERO).list();
        if (CollectionUtils.isNotEmpty(bomInfoLines)) {
            for (BomInfoLine line : bomInfoLines) {
                ConsumptionVO vo = new ConsumptionVO();
                vo.setItemCode(line.getItemCode());
                vo.setMakeLength(line.getMakeLength());
                vo.setMakeArea(line.getMakeArea());
                vo.setMakeNum(line.getMakeNum());
                ImmutablePair<String, String> pair = this.consumption(vo);
                if (StringUtils.isBlank(pair.getRight())) {
                    line.setItemConsumption(new BigDecimal(pair.getLeft()).setScale(2, RoundingMode.CEILING));
                    JpaUtil.update(line);
                }

            }

        }
    }

    @Transactional
    @Override
    public List<BomInfoLine> listSub(BomTreeVO vo) {
        List<BomInfoLine> bomInfoLines = JpaUtil.linq(BomInfoLine.class).equal("bomId", vo.getItemCode()).lessThanOrEqualTo("beginTime", vo.getDate()).greaterThan("endTime", vo.getDate()).list();
        if (CollectionUtils.isNotEmpty(bomInfoLines)) {
            Set<String> itemSet = bomInfoLines.stream().map(BomInfoLine::getItemCode).collect(Collectors.toSet());
            List<BomInfoLine> subLines = JpaUtil.linq(BomInfoLine.class).in("bomId", itemSet).lessThanOrEqualTo("beginTime", vo.getDate()).greaterThan("endTime", vo.getDate()).list();
            Set<String> existsItemSet = subLines.stream().map(BomInfoLine::getBomId).collect(Collectors.toSet());
            for (BomInfoLine line : bomInfoLines) {
                if (existsItemSet.contains(line.getItemCode())) {
                    line.setHasSub(true);
                } else {
                    line.setHasSub(false);
                }
            }
        }

        return bomInfoLines;
    }

    @Override
    @Transactional
    public Result<List<BomInfoLineVO>> inverseQuery(String itemCode, Date date) {

        List<BomInfoLine> lineList = JpaUtil.linq(BomInfoLine.class).equal("itemCode",itemCode).lessThanOrEqualTo("beginTime", date).greaterThan("endTime", date).list();
        if (CollectionUtils.isEmpty(lineList)){
            return Result.OK("该物料编码未被任何bom引用",new ArrayList<BomInfoLineVO>());
        }
        List<BomInfoLineVO> returnList = new ArrayList<>();
        for (BomInfoLine line :lineList){
            String bomId = line.getBomId();
            BomInfo bomInfo = JpaUtil.linq(BomInfo.class).equal("parentCode", bomId).lessThanOrEqualTo("beginTime", date).greaterThan("endTime", date).findOne();
            if (bomInfo!=null){
                String parentCode = bomInfo.getParentCode();//父类物料code
                List<String> topCodeList = new ArrayList<>();
                getTopBom(topCodeList,parentCode,date);
                if (topCodeList.size()>0){
                    //剔除父类
                    topCodeList.removeIf(next -> next.equals(parentCode));
                }
                if (topCodeList.size()>0){
                    for (String topCode:topCodeList){
                        BomInfoLineVO bomInfoLineVO = new BomInfoLineVO();
                        BeanReflectionUtils.copyProperties(bomInfoLineVO,line);

                        bomInfoLineVO.setParentCode(bomInfo.getParentCode());
                        bomInfoLineVO.setParentName(bomInfo.getParentName());
                        bomInfoLineVO.setParentUnit(bomInfo.getParentUnit());
                        bomInfoLineVO.setParentSpec(bomInfo.getParentSpec());
                        bomInfoLineVO.setParentDrawingNo(bomInfo.getParentDrawingNo());
                        BomInfo topBom = JpaUtil.linq(BomInfo.class).equal("parentCode", topCode).lessThanOrEqualTo("beginTime", date).greaterThan("endTime", date).findOne();
                        if (topBom!=null){
                            bomInfoLineVO.setTopCode(topBom.getParentCode());
                            bomInfoLineVO.setTopName(topBom.getParentName());
                            bomInfoLineVO.setTopUnit(topBom.getParentUnit());
                            bomInfoLineVO.setTopSpec(topBom.getParentSpec());
                            bomInfoLineVO.setTopDrawingNo(topBom.getParentDrawingNo());
                        }
                        returnList.add(bomInfoLineVO);
                    }
                }else{
                    BomInfoLineVO bomInfoLineVO = new BomInfoLineVO();
                    BeanReflectionUtils.copyProperties(bomInfoLineVO,line);

                    bomInfoLineVO.setParentCode(bomInfo.getParentCode());
                    bomInfoLineVO.setParentName(bomInfo.getParentName());
                    bomInfoLineVO.setParentUnit(bomInfo.getParentUnit());
                    bomInfoLineVO.setParentSpec(bomInfo.getParentSpec());
                    bomInfoLineVO.setParentDrawingNo(bomInfo.getParentDrawingNo());
                    returnList.add(bomInfoLineVO);
                }
            }
        }
        return Result.OK(returnList);
    }

    @Transactional
    public void getTopBom(List<String> topCodeList,String parentCode,Date date){
        List<BomInfoLine> lineList = JpaUtil.linq(BomInfoLine.class).equal("itemCode",parentCode).lessThanOrEqualTo("beginTime", date).greaterThan("endTime", date).list();
        if (CollectionUtils.isNotEmpty(lineList)){
            for (BomInfoLine line :lineList){
                String bomId = line.getBomId();
                getTopBom(topCodeList,bomId,date);
            }
        }else{
            topCodeList.add(parentCode);
        }
    }

    @Override
    @Transactional
    public List<BomInfoModel> getUnBomItemList() {
        List<Item> itemList = JpaUtil.linq(Item.class)
                .notExists(BomInfo.class)
                    .equalProperty("parentCode", "itemCode")
                    .equal("primaryBom", "1")
                .end()
                .equal("itemSource", "1").list();
        List<BomInfoModel> returnList = new ArrayList<>();
        if (itemList.size()>0){
            for (Item item:itemList){
                BomInfoModel bomInfoModel = new BomInfoModel();
                bomInfoModel.setParentGroup(item.getItemGroupCode());
                bomInfoModel.setParentCode(item.getItemCode());
                bomInfoModel.setParentName(item.getItemName());
                bomInfoModel.setParentDrawingNo(item.getDrawingNo());
                bomInfoModel.setParentSpec(item.getItemSpec());
                bomInfoModel.setParentUnit(item.getUnitCode());
                returnList.add(bomInfoModel);
            }
        }
        return returnList;
    }

    @Override
    @Transactional
    public Result<List<ProductBomStockAnalysisVO>> productBomStockAnalysis(String productItemCode, String referenceDate) {
        DateTime refDate = DateUtil.parseDate(referenceDate);
        if (refDate==null){
            return Result.error("参考日期格式有误，请检查。日期格式：yyyy-MM-dd，例如：2024-01-01");
        }
        VersionVO vo = new VersionVO();
        vo.setDate(refDate);
        BomInfo bomInfo = this.listBom(productItemCode, vo,true);
        if (bomInfo==null){
            return Result.error("未能在系统中匹配对应的BOM版本信息");
        }
        if(CollectionUtils.isEmpty(bomInfo.getBomInfoLineList())){
            return Result.error("BOM版本中的明细为空，无法分析");
        }

        Set<String> itemCodeSet = bomInfo.getBomInfoLineList().stream().map(BomInfoLine::getItemCode).collect(Collectors.toSet());//bominfo中的物料

        List<Item> itemList = JpaUtil.linq(Item.class).in("itemCode", itemCodeSet).list();
        Map<String, Item> itemMap = JpaUtil.index(itemList,"itemCode");//查询物料

        List<ItemMaterialProp> materialProps =  JpaUtil.linq(ItemMaterialProp.class).equal("propType", "item").in("code", itemCodeSet).list();//材料属性
        Map<String, ItemMaterialProp> materialPropMap = JpaUtil.index(materialProps,"code");

        List<ItemPlanProp> planProps =  JpaUtil.linq(ItemPlanProp.class).equal("propType", "item").in("code", itemCodeSet).list();//计划
        Map<String, ItemPlanProp> planPropMap = JpaUtil.index(planProps,"code");

        List<ProductBomStockAnalysisVO> bomItemList = new ArrayList<>();
        for(BomInfoLine line : bomInfo.getBomInfoLineList()){
            ProductBomStockAnalysisVO item = new ProductBomStockAnalysisVO();
            item.setItemCode(line.getItemCode());
            item.setItemName(line.getItemName());
            item.setItemSpec(line.getItemSpec());
            item.setLineNo(line.getLineNo());
            ItemPlanProp itemPlanProp = planPropMap.get(line.getItemCode());
            if (itemPlanProp!=null){
                item.setFeedingMode(itemPlanProp.getFeedingMode());
            }
            ItemMaterialProp itemMaterialProp = materialPropMap.get(line.getItemCode());
            if (itemMaterialProp!=null){
                item.setMaterialType(itemMaterialProp.getMaterialType());//材料类型
            }
            Item baseItem = itemMap.get(line.getItemCode());
            if (baseItem!=null){
                item.setItemGroupCode(baseItem.getItemGroupCode());
                item.setUnitCode(baseItem.getUnitCode());
                item.setDrawingNo(baseItem.getDrawingNo());
                item.setMaterialBrand(baseItem.getMaterialBrand());//材料牌号
            }
            item.setItemConsumption(line.getItemConsumption());//单机耗用量
            bomItemList.add(item);
        }
        Criteria lotStockCri = Criteria.create();
        lotStockCri.addCriterion("quantity", Operator.GT, BigDecimal.ZERO);//增加固定过滤条件 库存大于零
        lotStockCri.addCriterion("whCode",Operator.NE, "WH0005");//增加固定过滤条件 排除废品(不合格)仓
        List<VInvStock> stockList = invStockService.list(lotStockCri);
        if (stockList.isEmpty()){
            return Result.error("库存数据为空，无法分析！");
        }
        List<InvLotStockVO> stockVOList = new ArrayList<>();
        for (VInvStock stock:stockList){
            InvLotStockVO invLotStockVO = new InvLotStockVO();
            invLotStockVO.setWhCode(stock.getWhCode());
            invLotStockVO.setItemCode(stock.getItemCode());
            invLotStockVO.setQuantity(stock.getQuantity());
            stockVOList.add(invLotStockVO);//拷贝实时库存至对象
        }

        List<ProductBomStockAnalysisVO> returnList = new ArrayList<>();
        for (ProductBomStockAnalysisVO orderItem:bomItemList){
            orderItem.setKittingQuantity(BigDecimal.ZERO);//置零
            orderItem.setSetQuantity(BigDecimal.ZERO);//成套数量置零
            BigDecimal quantity = new BigDecimal("100000000");//默认指定一个很大的数量
            BigDecimal restQuantity = quantity;
            BigDecimal kittingQuantity = BigDecimal.ZERO;//齐套匹配库存数量

            String itemCode = orderItem.getItemCode();
            List<InvLotStockVO> matchStockList  = stockVOList.stream().filter(lotStock -> lotStock.getItemCode().equals(itemCode)).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(matchStockList)){
                for (InvLotStockVO next : matchStockList) {
                    BigDecimal stockQuantity = next.getQuantity();
                    if (stockQuantity.compareTo(BigDecimal.ZERO) > 0) {//有库存的情况
                        if (stockQuantity.compareTo(restQuantity) >= 0) {//库存大于行数量
                            kittingQuantity = kittingQuantity.add(restQuantity);
                            next.setQuantity(stockQuantity.subtract(restQuantity));
                            break;
                        } else {
                            kittingQuantity = kittingQuantity.add(stockQuantity);
                            restQuantity = restQuantity.subtract(stockQuantity);
                            next.setQuantity(BigDecimal.ZERO);//库存数量置
                        }
                    }
                }
                orderItem.setStockLiveQuantity(kittingQuantity);
                orderItem.setKittingQuantity(kittingQuantity);
                orderItem.setSetQuantity(kittingQuantity.divide(orderItem.getItemConsumption(),2,BigDecimal.ROUND_HALF_UP));
            }
            /*if(orderItem.getKittingQuantity().compareTo(BigDecimal.ZERO)==0){
                orderItem.setAnalysisColor("red");
            } else if(orderItem.getKittingQuantity().compareTo(quantity)==0){
                orderItem.setAnalysisColor("green");
            } else{
                orderItem.setAnalysisColor("yellow");
            }*/
            returnList.add(orderItem);
        }
        ProductBomStockAnalysisVO min = returnList.stream().min(Comparator.comparing(ProductBomStockAnalysisVO::getSetQuantity)).get();
        return Result.OK(min.getSetQuantity().toPlainString(),returnList);
    }

    @Override
    @Transactional
    public Page<BomInfo> copyTargetPage(Pageable page, Criteria criteria) {
        Linq linq = JpaUtil.linq(Item.class)
                .notExists(BomInfo.class)
                    .equalProperty("parentCode", "itemCode")
                .end()
                .notExists(BomInfoAudit.class)
                    .equalProperty("parentCode", "itemCode")
                    .equal("useType", OrderStatusEnums.BomStatus.USING.getStatusCode())
                .end()
                .notExists(BomInfoTmp.class)
                    .equalProperty("parentCode", "itemCode")
                .end()
                .equal("itemSource", "1")
                .where(criteria);
        Page<Item> itemPage = linq.paging(page);
        Long count = linq.count();

        List<Item> itemList = itemPage.getContent();
        List<BomInfo> returnList = new ArrayList<>();
        if (!itemList.isEmpty()){
            for (Item item : itemList) {
                BomInfo bomInfo = new BomInfo();
                bomInfo.setParentCode(item.getItemCode());
                bomInfo.setParentName(item.getItemName());
                bomInfo.setParentGroup(item.getItemGroupCode());
                bomInfo.setParentSpec(item.getItemSpec());
                bomInfo.setParentUnit(item.getUnitCode());
                bomInfo.setParentDrawingNo(item.getDrawingNo());
                returnList.add(bomInfo);
            }
        }
        return new PageImpl<>(returnList, page, count);
    }
}
